package com.lfk.justwetools.Component.MarkDown;

import com.lfk.justwetools.Utils.Log;
import com.lfk.justwetools.Utils.ProgressDialog;
import ohos.agp.components.webengine.*;
import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.agp.components.AttrSet;
import ohos.global.resource.Resource;
import ohos.utils.net.Uri;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLConnection;
import java.nio.charset.Charset;

/**
 * Created by liufengkai on 15/10/3.
 */
public class MarkDownView extends WebView {

    private Context context;
    private ProgressDialog progressDialog = null;
    private final String STYLE_DIR = "https://example.com/rawfile/";      //样式保存地址
    private final static String LOAD_HTML = "https://example.com/rawfile/markdown.html";
    private String str = "";

    public MarkDownView(Context context) {
        super(context);
        init(context);
    }

    public MarkDownView(Context context, AttrSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context){
        this.context = context;
        progressDialog = ProgressDialog.show(context, "请等待", "正在载入...", true);
//        this.setScrollBarStyle(SCROLLBARS_INSIDE_OVERLAY);
//        this.getSettings().setBuiltInZoomControls(true);
//        this.getSettings().setDisplayZoomControls(false);
//        this.getSettings().setJavaScriptEnabled(true);
//        this.getSettings().setLoadWithOverviewMode(true);
//        this.getSettings().setUseWideViewPort(true);
//        this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//        this.getSettings().setAppCacheEnabled(true);
//        this.getSettings().setCacheMode(this.getSettings().LOAD_CACHE_ELSE_NETWORK);

        WebConfig webConfig = getWebConfig();
        webConfig.setJavaScriptPermit(true);
        webConfig.setViewPortFitScreen(true);

        load(LOAD_HTML);
        this.setBrowserAgent(new BrowserAgent(context) {
            @Override
            public void onProgressUpdated(WebView webView, int newProgress) {
                super.onProgressUpdated(webView, newProgress);
                if (newProgress >= 100 && progressDialog.isShowing()) {
                    progressDialog.destroy();
                }
            }
        });

        this.setWebAgent(new WebAgent() {
            @Override
            public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
                final String authority = "example.com";
                final String rawFile = "/rawfile/";
                Uri requestUri = request.getRequestUrl();
                if (authority.equals(requestUri.getDecodedAuthority())) {
                    String path = requestUri.getDecodedPath();
                    if (TextTool.isNullOrEmpty(path)) {
                        return super.processResourceRequest(webView, request);
                    }
                    if (path.startsWith(rawFile)) {
                        String rawFilePath = "simple/resources/rawfile/" + path.replace(rawFile, "");
                        String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                        try {
                            Resource resource = getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                            ResourceResponse response = new ResourceResponse(mimeType, resource, null);
                            return response;
                        } catch (IOException e) {
                            Log.i("open raw file failed");
                        }
                    }
                }
                return super.processResourceRequest(webView, request);
            }
        });
    }

    public void setDirSource(File dir){
        try {
            FileInputStream in = new FileInputStream(dir);
            ByteArrayOutputStream bufferOut = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];

            for(int i = in.read(buffer, 0, buffer.length); i > 0 ; i = in.read(buffer, 0, buffer.length)) {
                bufferOut.write(buffer, 0, i);
            }
            str = new String(bufferOut.toByteArray(), Charset.forName("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.load(LOAD_HTML);
        setUpWebView(str);
    }

    public void setStringSource(String str){
        this.str = str;
        this.load(LOAD_HTML);
        setUpWebView(str);
    }

    private void loadMarkDown(String str) {
        executeJs("javascript:parseMarkdown(\"" + str + "\")", null);
    }

    private void setUpWebView(final String mdText) {
        this.setWebAgent(new WebAgent(){
            @Override
            public void onPageLoaded(WebView webView, String url) {
                super.onPageLoaded(webView, url);
                loadMarkDown(mdText.replaceAll("(\\r|\\n|\\r\\n)+", "\\\\n"));
            }

            @Override
            public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
                final String authority = "example.com";
                final String rawFile = "/rawfile/";
                Uri requestUri = request.getRequestUrl();
                if (authority.equals(requestUri.getDecodedAuthority())) {
                    String path = requestUri.getDecodedPath();
                    if (TextTool.isNullOrEmpty(path)) {
                        return super.processResourceRequest(webView, request);
                    }
                    if (path.startsWith(rawFile)) {
                        String rawFilePath = "simple/resources/rawfile/" + path.replace(rawFile, "");
                        String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                        try {
                            Resource resource = getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                            ResourceResponse response = new ResourceResponse(mimeType, resource, null);
                            return response;
                        } catch (IOException e) {
                            Log.i("open raw file failed");
                        }
                    }
                }
                return super.processResourceRequest(webView, request);
            }
        });
        this.setBrowserAgent(new BrowserAgent(mContext) {
            @Override
            public void onProgressUpdated(WebView webView, int newProgress) {
                super.onProgressUpdated(webView, newProgress);
                if (newProgress >= 100 && progressDialog.isShowing()) {
                    progressDialog.destroy();
                }
            }
        });
    }


}
